import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
// 设置axios的基础URL
axios.defaults.baseURL = 'https://www.you04.cn'
export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || sessionStorage.getItem('token'))
  const users = ref([])
  const userInfo = ref({
    id: null,
    username: '',
    email: '',
    avatar: '',
    roles: []
  })
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasRole = computed(() => (role) => {
    return userInfo.value.roles.includes(role)
  })
  const pagination = ref({
    page: 1,
    pageSize: 10,
    total: 0
  });
  // 操作
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setUserInfo = (info) => {
    userInfo.value = { ...info }
  }
  //获取当前登录用户信息
  const getUserProfile = async () => {
    try {
      const response = await axios.get('/api/auth/profile', {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data.data; // 假设后端返回用户信息
    } catch (error) {
      throw error
    }
  }
  //获取列表
  const userslist = async (paginationParams = {}) => {
    try {
      const response = await axios.get('/api/users', {
        headers: {
          'Authorization': `Bearer ${token.value}`
        },
        params: {
          page: paginationParams.page || pagination.value.page,
          size: paginationParams.pageSize || pagination.value.pageSize
        }
      });
      const { items, totalCount, pageIndex, pageSize } = response.data.data;
      users.value = items;
      pagination.value = {
        page: pageIndex,
        pageSize: pageSize,
        total: totalCount
      };
      return { users: users.value, pagination: pagination.value }
      // 假设后端返回用户列表
    } catch (error) {
      console.error('获取用户列表错误:', error);
      throw new Error(error.response?.data?.message || 'fetch_users_failed');
    }
  }
  // 搜索用户
  const searchUsers = async (searchParams, paginationParams = {}) => {
    try {
      const params = {
        page: paginationParams.page || pagination.value.page,
        size: paginationParams.pageSize || pagination.value.pageSize
      };

      if (searchParams.username) params.userName = searchParams.username;
      if (searchParams.email) params.email = searchParams.email;

      const response = await axios.get('/api/users/search', {
        headers: {
          'Authorization': `Bearer ${token.value}`
        },
        params
      });

      const { items, totalCount, pageIndex, pageSize } = response.data.data;
      users.value = items;
      pagination.value = {
        page: pageIndex,
        pageSize: pageSize,
        total: totalCount
      };
      return { users: users.value, pagination: pagination.value }
    } catch (error) {
      console.error('搜索用户错误:', error);
      throw new Error(error.response?.data?.message || 'search_users_failed');
    }
  };

  //添加用户
  const adduser = async (user) => {
    try {
      const response = await axios.post('/api/users', user, {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data; // 后端返回添加的用户信息
    } catch (error) {
      throw new Error(error.response?.data?.message || 'add_user_failed');
    }
  }
  //删除用户
  const deleteuser = async (userId) => {
    try {
      const response = await axios.delete(`/api/users/${userId}`, {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      return response.data; // 后端返回删除结果
    } catch (error) {
      throw new Error(error.response?.data?.message || 'delete_user_failed');
    }
  }
  //修改用户
  const updateUser = async (userId, userData) => {
    try {
      const response = await axios.put(`/api/users/${userId}`, userData, {
        headers: { 'Authorization': `Bearer ${token.value}` }
      });
      return response.data; // 后端返回更新后的用户信息
    } catch (error) {
      throw new Error(error.response?.data?.message || 'update_user_failed');
    }
  }

  // 更新当前用户个人信息
  const updateProfile = async (profileData) => {
    try {
      const response = await axios.put('/api/users/profile', profileData, {
        headers: { 'Authorization': `Bearer ${token.value}` }
      });
      return response.data;
    } catch (error) {
      throw new Error(error.response?.data?.message || 'update_profile_failed');
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    try {
      const response = await axios.put('/api/users/change-password', passwordData, {
        headers: { 'Authorization': `Bearer ${token.value}` }
      });
      return response.data;
    } catch (error) {
      throw new Error(error.response?.data?.message || 'change_password_failed');
    }
  }

  // 获取当前用户的操作日志
  const getUserLogs = async (page = 1, pageSize = 10) => {
    try {
      const currentUserId = userInfo.value.id;
      const response = await axios.get('/api/operation-logs', {
        headers: { 'Authorization': `Bearer ${token.value}` },
        params: {
          userId: currentUserId,
          page,
          size: pageSize
        }
      });
      return response.data.data;
    } catch (error) {
      throw new Error(error.response?.data?.message || 'fetch_user_logs_failed');
    }
  }

  // 上传头像
  const uploadAvatar = async (formData) => {
    try {
      console.log('开始上传头像...');

      // 先上传文件
      const uploadResponse = await axios.post('/api/files/upload', formData, {
        headers: {
          'Authorization': `Bearer ${token.value}`,
          'Content-Type': 'multipart/form-data'
        }
      });

      console.log('文件上传成功:', uploadResponse.data);
      const fileUrl = uploadResponse.data.data.url;

      // 获取当前用户信息
      console.log('获取当前用户信息...');
      const currentUser = await getUserProfile();
      console.log('当前用户信息:', currentUser);

      // 然后更新用户头像字段，包含必需的email字段
      console.log('更新用户头像...');

      // 构建更新数据，只包含必需的字段和有效的可选字段
      const updateData = {
        email: currentUser.email, // 必需字段
        avatar: fileUrl // 新头像
      };

      // 只在 phone 有有效值时才包含它
      if (currentUser.phone && currentUser.phone.trim() !== '') {
        updateData.phone = currentUser.phone;
      }

      console.log('更新数据:', updateData);
      console.log('Phone值的详细信息:', {
        originalPhone: currentUser.phone,
        phoneType: typeof currentUser.phone,
        phoneLength: currentUser.phone?.length,
        phoneIsNull: currentUser.phone === null,
        phoneIsUndefined: currentUser.phone === undefined,
        phoneIsEmptyString: currentUser.phone === '',
        includePhoneInUpdate: !!updateData.phone
      });

      const updateResponse = await axios.put('/api/users/profile', updateData, {
        headers: { 'Authorization': `Bearer ${token.value}` }
      });

      console.log('头像更新成功:', updateResponse.data);
      return updateResponse.data;
    } catch (error) {
      console.error('头像上传错误详情:', error);
      console.error('错误响应:', error.response);
      if (error.response) {
        console.error('响应数据:', error.response.data);
        console.error('响应状态:', error.response.status);
        console.error('响应头:', error.response.headers);
        // 打印验证错误的详细信息
        if (error.response.data && error.response.data.errors) {
          console.error('验证错误详情:', error.response.data.errors);
        }
      }

      const errorMessage = error.response?.data?.message ||
        error.response?.data?.error ||
        error.message ||
        'upload_avatar_failed';
      throw new Error(errorMessage);
    }
  }
  return {
    // 状态
    token,
    userInfo,

    // 计算属性
    isLoggedIn,
    hasRole,

    // 操作
    setToken,
    setUserInfo,
    getUserProfile,
    userslist,
    searchUsers,
    adduser,
    deleteuser,
    updateUser,
    updateProfile,
    changePassword,
    getUserLogs,
    uploadAvatar
  }
})
